// pages/statement/statement.js
let app = getApp()
let request = require('../../utils/request')
import * as echarts from '../../components/ec-canvas/echarts';
let chartLine;
let chartDoughnut;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageAllHeight: app.globalData.pageAllHeight,
    pageHeight: app.globalData.pageHeight,
    parkId: 0,
    tabIndex: 1,
    dataTypeList: [1, 2, 3, 4, 5],
    parkPayMoney: 0,
    monthPayMoney: 0,
    subscribePayMoney: 0,
    LinkIndexMax: 0,
    LinkIndexMin: 0,
    ecLine: {
      lazyLoad: true
    },
    ecdoughnut: {
      lazyLoad: true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      parkId: wx.getStorageSync('lmtc_admin_parkInfo').parkId
    })
    this.getPayInfo()
    this.getLinkIndex()
    this.getProportion()
  },
  onReady: function () {
    // 获取组件
    this.mychartEcLine = this.selectComponent('#mychart-ecLine');
    this.mychartEcdoughnut = this.selectComponent('#mychart-ecdoughnut');
  },
  /**
   * 切换bar
   */
  selectBar(e) {
    let index = e.currentTarget.dataset.index
    let tabIndex = this.data.tabIndex
    if (tabIndex == index) {
      return
    }
    this.setData({
      tabIndex: index
    })
    this.getPayInfo()
  },
  /**
   * 获取缴费记录
   */
  getPayInfo() {
    this.getParkPay()
    this.getMonthPay()
    this.getSubscribePay()
  },
  /**
   * 获取泊车缴费
   */
  getParkPay() {
    let that = this
    let dateType = this.data.tabIndex
    let url = '/order/orderInfo/getOrderRevenue'
    let parmas = {
      dateType: dateType,
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            parkPayMoney: data.data
          })
        }
      })
  },
  /**
   * 获取月租缴费
   */
  getMonthPay() {
    let that = this
    let dateType = this.data.tabIndex
    let url = '/order/orderInfo/getMonthRevenue'
    let parmas = {
      dateType: dateType,
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            monthPayMoney: data.data
          })
        }
      })
  },
  /**
   * 获取预约缴费
   */
  getSubscribePay() {
    let that = this
    let dateType = this.data.dataTypeList[this.data.tabIndex]
    let url = '/order-reserve/park-reserve-record/get-reserve-amount-by-date'
    let parmas = {
      dateType: dateType,
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            subscribePayMoney: data.data
          })
        }
      })
  },
  /**
   * 总收益环比分析
   */
  getLinkIndex() {
    let that = this
    let url = '/order/orderInfo/get-month-income'
    let parmas = {
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let earnings = data.data
          var earningArr = []
          for (var i = 0; i < earnings.length; i++) {
            earningArr.push([earnings[i], i+1])
          }
          earningArr.sort(function (a, b) {
            return a[0] - b[0]
          })
          that.setData({
            LinkIndexMax: earningArr[earningArr.length - 1],
            LinkIndexMin: earningArr[0]
          })
          // 重置柱状图
          this.mychartEcLine.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            getOption(chart, earnings);
            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
          });
        }
      })
  },
  /**
   * 总收益占比分析
   */
  getProportion() {
    let that = this
    let url = '/order/orderInfo/income'
    let parmas = {
      parkId: that.data.parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let earnings = data.data
          var xData = []
          xData.push(earnings.parkIncome)
          xData.push(earnings.monthIncome)
          xData.push(earnings.reserveIncome)
          this.mychartEcdoughnut.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            getOptionDoughnut(chart, xData);
            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
          });
        }
      })
  }
})
function getOption(chart, xData) {
  var option = {
    color: ['#3398DB'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '0',
      right: '0',
      bottom: '0',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        itemStyle: {
          // normal是柱状图的正常样式
          normal: {
            barBorderRadius: [30, 30, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [
              {
                offset: 1,
                color: '#5273F7'
              },
              {
                offset: 1,
                color: '#859DFF'
              }
            ]
            ),
          },
          // 移入当前的柱状图时改变颜色
          emphasis: {
            color: '#5273F7',
          }
        },
        type: 'bar',
        barWidth: '60%',
        data: xData
      }
    ]
  };
  chart.setOption(option);
}
function getOptionDoughnut(chart, xData) {
  var option = {
    tooltip: {
      trigger: 'item',
    },
    series: [
      {
        // name: '总收益占比分析',
        type: 'pie',
        radius: ['30%', '50%'],
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        label: {
          normal: {
            formatter: '{b}\n{d}%',
            lineHeight: 18,
          }
        },
        data: [
          { value: xData[0], name: '泊车费', itemStyle: { color: '#2381FD' } },
          { value: xData[1], name: '月租费', itemStyle: { color: '#F8763B' } },
          { value: xData[2], name: '预约费', itemStyle: { color: '#33D4C1' } },
        ]
      }
    ]
  };
  chart.setOption(option);
}